import { message } from "@/utils/message";
import axios from "axios";
import type { CustomError, CustomRequestConfig } from "./types";

/**
 * 处理请求错误
 * @param error 原始错误
 * @param clearToken 清除token的回调函数
 * @returns 处理后的错误
 */
export const handleRequestError = async (
  error: any,
  clearToken?: () => void
): Promise<CustomError> => {
  const customError = error as CustomError;

  // 处理取消请求的情况
  if (axios.isCancel(error)) {
    customError.isCancel = true;
    customError.message = "请求已取消";
    return customError;
  }

  // 处理超时错误
  if (error.code === "ECONNABORTED" || error.message?.includes("timeout")) {
    customError.isTimeout = true;
    customError.message = "请求超时";
    return customError;
  }

  // 处理网络错误
  if (!error.response) {
    customError.isNetworkError = true;
    customError.message = "网络异常，请检查您的网络连接";
    return customError;
  }

  // 处理 HTTP 状态码错误
  const { status } = error.response;
  // 不再基于HTTP状态码处理权限错误，而是将其统一为普通HTTP错误
  switch (status) {
    case 400:
      customError.message = "请求参数错误";
      break;
    case 401:
      // 不再在这里处理权限错误
      customError.message = "HTTP 401 错误";
      break;
    case 403:
      // 不再在这里处理权限错误
      customError.message = "HTTP 403 错误";
      break;
    case 404:
      customError.message = "请求的资源不存在";
      break;
    case 500:
      customError.message = "服务器错误";
      break;
    default:
      customError.message = `未知HTTP错误：${status}`;
  }

  return customError;
};

/**
 * 处理业务逻辑错误
 * @param response 响应对象
 * @param config 请求配置
 * @param clearToken 清除token的回调函数（用于权限错误处理）
 * @returns 是否为业务逻辑错误，如果是则返回错误对象
 */
export const handleBusinessError = (
  response: any,
  config: CustomRequestConfig,
  clearToken?: () => void
): { isError: boolean; error?: CustomError } => {
  const { data } = response;

  if (data && typeof data === "object") {
    // 首先检查是否是权限错误 (401, 403)
    if (data.code === 401) {
      if (!config.skipErrorHandler) {
        const error: CustomError = new Error("未授权，请重新登录");
        error.name = "AuthError";
        error.code = data.code;
        error.config = {
          url: config.url,
          method: config.method,
          baseURL: config.baseURL
        };
        error.response = {
          status: response.status,
          statusText: response.statusText,
          data: {
            code: data.code,
            message: data.message || "未授权，请重新登录",
            success: false
          }
        };
        error.isBusinessError = true;
        error.isAuthError = true;

        // 执行清除token操作
        if (clearToken) {
          clearToken();
        }
        // 可以在这里添加跳转到登录页的逻辑

        return { isError: true, error };
      }
    } else if (data.code === 403) {
      if (!config.skipErrorHandler) {
        const error: CustomError = new Error("拒绝访问，权限不足");
        error.name = "ForbiddenError";
        error.code = data.code;
        error.config = {
          url: config.url,
          method: config.method,
          baseURL: config.baseURL
        };
        error.response = {
          status: response.status,
          statusText: response.statusText,
          data: {
            code: data.code,
            message: data.message || "拒绝访问，权限不足",
            success: false
          }
        };
        error.isBusinessError = true;
        error.isForbiddenError = true;

        return { isError: true, error };
      }
    }
    // 检查一般业务错误: code不等于200或success不为true
    else if (data.code !== 200 || data.success === false) {
      if (!config.skipErrorHandler) {
        const error: CustomError = new Error(data.message || "业务处理异常");
        error.name = "BusinessError";
        error.code = data.code;
        error.config = {
          url: config.url,
          method: config.method,
          baseURL: config.baseURL
        };
        error.response = {
          status: response.status,
          statusText: response.statusText,
          data: {
            code: data.code,
            message: data.message,
            success: false
          }
        };
        error.isBusinessError = true;
        message(data.message, { type: "error" });

        return { isError: true, error };
      }
    }
  }

  return { isError: false };
};
